package io.github.biezhi.elves.examples;

import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.os.WindowsUtils;

//import com.dama2.Dama2Web;

import io.github.biezhi.elves.common.Constants;
import io.github.biezhi.elves.utils.BaiduApiUtils;
import io.github.biezhi.elves.utils.CreateElementScreenshot;
import io.github.biezhi.elves.utils.StringUtils;
import io.github.biezhi.elves.utils.WebDriverUtils;

public class ChromeExample {
	// static String url =
	// "http://www.qichacha.com/search?key=*%E9%BC%8E%E6%B9%96%E5%8C%BA%E6%A1%82%E5%9F%8E%E5%AE%9E%E6%83%A0%E7%99%BE%E8%B4%A7%E5%BA%97";
	static String url = "http://www.qichacha.com/user_login";
	// static String url = "http://www.gsxt.gov.cn/socialuser-use-login.html";

	public static void main(String[] args) throws IOException {
//		testBaiduByJS();
		
		getLoginQccForCookie("");
		
//		System.err.println(StringUtils.findProcess(Constants.CHROME_PROCESS_NAME));
	}
	
	/**
	 * 测试自动化模拟登陆企查查返回登陆后cookie信息
	 */
	private static String getLoginQccForCookie(String url) {
		url = "http://www.qichacha.com/index_verify?type=companyview&back=/firm_df1b36927d6f2edd80dff5554e3f8cd6.html?companyname=1295%EF%BC%88%E8%90%A5%E8%BF%90%E7%89%8C%E5%8F%B7%EF%BC%89&entname=1295%EF%BC%88%E8%90%A5%E8%BF%90%E7%89%8C%E5%8F%B7%EF%BC%89";
		url = "http://www.qichacha.com/user_login?back=http://www.qichacha.com/search?key=1104%EF%BC%88%E8%90%A5%E8%BF%90%E7%89%8C%E5%8F%B7%EF%BC%89";
		url = "http://www.qichacha.com/user_login";
//		url = "http://www.qichacha.com/search?key=1354%EF%BC%88%E8%90%A5%E8%BF%90%E7%89%8C%E5%8F%B7%EF%BC%89&entname=1354%EF%BC%88%E8%90%A5%E8%BF%90%E7%89%8C%E5%8F%B7%EF%BC%89";
//		url = "http://www.qichacha.com/index_verify?type=companysearch&back=/search?key=%E4%B8%80%E7%B1%B3%E4%B9%9D%E5%85%AB%E5%A4%9C%E6%80%BB%E4%BC%9A";
		
		try{
			//检测程序
			if(!StringUtils.findProcess(Constants.CHROME_PROCESS_NAME) && StringUtils.findProcess(Constants.CHROME_DRIVER_PROCESS_NAME)){
				//检测并杀掉程序
				StringUtils.findAndKillProcess(Constants.CHROME_DRIVER_PROCESS_NAME);
			}
			// 1、开启个浏览器并且输入链接
			WebDriver driver = WebDriverUtils.getChromeDriver(url);
			
			List<WebElement> errorElement = driver.findElements(By.cssSelector(".message"));
			if(errorElement!=null && errorElement.size()>0){
				String errorText = errorElement.get(0).getText();
				if(errorText.equals(Constants.QCC_ERROR_CONTENT)){
					driver.quit();
					String requestUrl = Constants.QCC_BACK_URL1 + url;
					driver = WebDriverUtils.getChromeDriver(requestUrl);
				}
			}
			
			// 2、点击频繁页面【登录】按钮
			List<WebElement> loginElements = driver.findElements(By.cssSelector("a[href=\"/user_login\"]"));
			if(loginElements!=null && loginElements.size()>0){
				WebElement loginElement = driver.findElement(By.cssSelector("a[href=\"/user_login\"]"));
				WebDriverUtils.scrollToElementAndClick(loginElement, driver);
			}
			
			// 休息3秒，加载数据
			try {
				Thread.sleep(3000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			
//			System.out.println("开始执行刷新页面操作。。。");
//			driver.navigate().refresh();
//			System.out.println("结束执行刷新页面操作。。。");
			
			List<WebElement> nameNormalElements = driver.findElements(By.id("nameNormal"));
			if(nameNormalElements!=null && nameNormalElements.size()>0){
				WebDriverUtils.inputStrByJS(driver, "nameNormal", "13710729639");
				WebDriverUtils.inputStrByJS(driver, "pwdNormal", "290990www");
			}
			
			Actions action = new Actions(driver);
//			WebDriverUtils.refresh(driver, action);
			
			//执行滑块操作,拖动滑块最右边
			moveSliderToRight(driver,action);
			
			// 休息3秒，加载数据
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			// 释放鼠标
			action.release();
			
			//点击滑块处【刷新】按钮
//			clickReloadSlider(driver,action);
			
			//图片识别
			discernImgCode(driver, action);
			
			//点击【验证一下】按钮
	//		WebElement verifyElement = driver.findElement(By.id("verify"));
	//		verifyElement.click();
			
			//点击【会员登录】按钮
			List<WebElement> submitLoginElements = driver.findElements(By.xpath("//*[@id=\"user_login_normal\"]/button/strong"));
			if(submitLoginElements!=null && submitLoginElements.size()>0){
				System.out.println("点击【会员登录】按钮......");
				WebElement submitLoginElement = driver.findElement(By.xpath("//*[@id=\"user_login_normal\"]/button/strong"));
				WebDriverUtils.scrollToElementAndClick(submitLoginElement, driver);
			}
			
			// 休息3秒，加载数据
			try {
				Thread.sleep(2000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			
			//向浏览器添加cookie信息
			System.out.println("向浏览器添加cookie信息......");
			String qccCookie = WebDriverUtils.getBrowserCookies(driver);
			System.out.println("qccCookie{{}}==>" + qccCookie);
//			driver.quit();
			return qccCookie;
		}catch(Exception e){
			System.out.println("异常{{}}==>");
//			WindowsUtils.tryToKillByName("chromedriver.exe");
		}
		return "";
	}
	
	/**
	 * 识别图片验证码
	 * @param driver
	 * @param action
	 */
	private static void discernImgCode(WebDriver driver,Actions action) {
		List<WebElement> contentCodeElements = driver.findElements(By.id("nc_1__scale_text"));
		if(contentCodeElements!=null && contentCodeElements.size()>0){
			WebElement contentCodeElement = driver.findElement(By.id("nc_1__scale_text"));
			String contentCodeText = contentCodeElement.getText();
			contentCodeText = contentCodeText.replace("请点击图中的“", "").replace("”字", "");
			
			List<WebElement> imgElements = driver.findElements(By.cssSelector(".clickCaptcha_img > img"));
			if(imgElements!=null && imgElements.size()>0){
				WebElement imgElement = driver.findElement(By.cssSelector(".clickCaptcha_img > img"));
				try {
					String filePathOne = "f:/scale_text.png";
					String filePathTwo = "f:/clickCaptcha.png";
					String mergeImgFilePath = "f:/hebing.png";
					FileUtils.copyFile(CreateElementScreenshot.captureElement(imgElement), new File(filePathTwo));
					BufferedImage scaleTextImg = CreateElementScreenshot.getImageWidthAndHeight(filePathTwo);
					FileUtils.copyFile(CreateElementScreenshot.captureElement(contentCodeElement,scaleTextImg.getWidth()), new File(filePathOne));
					
					//两张图合并成一张图(两张图的宽度必须一致)
					CreateElementScreenshot.mergeImage(filePathOne, filePathTwo, mergeImgFilePath);
					
					// 休息2秒，加载数据
//					try {
//						Thread.sleep(2000);
//					} catch (InterruptedException e) {
//						e.printStackTrace();
//					}
					
					System.out.println("开始识别图中文字位置坐标......");
					String pointXY = BaiduApiUtils.getBaiduOcrLocation(mergeImgFilePath,contentCodeText);
					if(!StringUtils.isNullOrEmpty(pointXY)) {
						String[] pointXYs = pointXY.split(",");
						int x = Integer.parseInt(pointXYs[0].trim());
						int y = Integer.parseInt(pointXYs[1].trim());
						
						System.out.println("x==>" + x + "，y==>" + y);
						
						action.moveToElement(imgElement, x + 2, y - 34).click().perform();
					} else {
						List<WebElement> refreshImgCodeElements = driver.findElements(By.xpath("//*[@id=\"nc_1__btn_2\"]"));
						if(refreshImgCodeElements!=null && refreshImgCodeElements.size()>0){
							WebElement refreshImgCodeElement = driver.findElement(By.xpath("//*[@id=\"nc_1__btn_2\"]"));
							refreshImgCodeElement.click();
							
							// 休息2秒，加载数据
							try {
								Thread.sleep(2000);
							} catch (InterruptedException e) {
								e.printStackTrace();
							}
							
							discernImgCode(driver, action);
						}
					}
					
//					String pointXY = Dama2Web.getDama2ImgPoint(mergeImgFilePath,true);
//					if(!StringUtils.isNullOrEmpty(pointXY)){
//						String[] pointXYs = pointXY.split(",");
//						int x = Integer.parseInt(pointXYs[0].trim());
//						int y = Integer.parseInt(pointXYs[1].trim());
//						action.moveToElement(imgElement, x+2, y-34).click().perform();
//					}
					System.out.println("识别图中文字位置坐标完成,坐标为{{}}==>" + pointXY);
				} catch (Exception e) {
					System.out.println("识别图中文字调用接口异常,异常信息如下{{}}==>" + StringUtils.getErrorInfoFromException(e));
				}
			}
		}
	}
	
	/**
	 * 拖动滑块最右边
	 * @param driver
	 * @param action
	 */
	private static void moveSliderToRight(WebDriver driver,Actions action){
		int offset = 10;
		int maxOffset = 80;
		List<WebElement> draggers = driver.findElements(By.xpath("//*[@id=\"nc_1_n1z\"]"));
		if(draggers!=null && draggers.size()>0){
			WebElement dragger = driver.findElement(By.xpath("//*[@id=\"nc_1_n1z\"]"));
			action.clickAndHold(dragger).build().perform();
			
			for(int i=10;i<=maxOffset;i=i+10){
				try {
					int moveOffset = offset + i;
					Thread.sleep(2000);
					action.moveByOffset(moveOffset, 0).perform();
					if(moveOffset>=maxOffset){
						break;
					}
				} catch (Exception e) {
					System.out.println("执行滑块异常,异常信息如下{{}}==>" + StringUtils.getErrorInfoFromException(e));
				}
			}
		}
	}
	
	/**
	 * 点击滑块处【刷新】按钮
	 * @param driver
	 * @param action
	 */
	private static void clickReloadSlider(WebDriver driver,Actions action){
		List<WebElement> reloadDivElements = driver.findElements(By.cssSelector(".errloading"));
		if(reloadDivElements!=null && reloadDivElements.size()>0){
			WebElement err = driver.findElement(By.xpath("//*[@id=\"dom_id_one\"]/div/span/a"));
			err.click();
			
			// 休息2秒，加载数据
			try {
				Thread.sleep(2000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			
			//再次执行滑块操作,拖动滑块最右边
			moveSliderToRight(driver,action);
		}
	}

	/**
	 * 测试向input标签输入值
	 */
	// @Test
	public static void testBaiduByJS() {
		// 1、开启个浏览器并且输入链接
		WebDriver driver = WebDriverUtils.getChromeDriver("https://www.baidu.com/");

		// 2、向百度输入框输入需要查询的值
		WebDriverUtils.inputStrByJS(driver, "kw", "爱情");

		// 3、得到百度一下的标签
		WebElement submitElement = driver.findElement(By.cssSelector("input#su"));

		// 4、点击百度一下
		WebDriverUtils.scrollToElementAndClick(submitElement, driver);

		// 休息3秒，加载数据
		try {
			Thread.sleep(3000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

		// 5、首先找到 id 为 content_left 的 div 下面的所有 div
		List<WebElement> divElements = driver.findElements(By.cssSelector("div#content_left div"));
		// 6、找到搜索的第一个链接
		WebElement aElement = divElements.get(0).findElement(By.cssSelector("div.f13 a[href]"));

		// 7、点击该链接
		WebDriverUtils.scrollToElementAndClick(aElement, driver);
	}
}